package ten;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.*;

public class CRacer implements Callable<Integer> {
    private static Map<String, String> racer = new HashMap<String, String>(){{
//        put("pool-1-thread-1", "rabbit");
//        put("pool-1-thread-2", "tortoise");
        put("pool-1-thread-1", "兔子");
        put("pool-1-thread-2", "乌龟");
    }};
    private static String winner;

    @Override
    public Integer call() throws Exception {
        for (int i = 1; i <= 100; i++) {
            if (Thread.currentThread().getName().equals("pool-1-thread-1") && i % 10 == 0) {
                Thread.sleep(1);
            }
            System.out.println(Thread.currentThread().getName() + "--->" + i);
            if (gameOver(i)) {
                return i;
            }
        }
        return null;
    }

    private boolean gameOver(int step) {
        if (winner != null) {
            return true;
        } else {
            if (step == 100) {
                winner = Thread.currentThread().getName();
                System.out.println("winner: " + racer.get(winner));
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CRacer rac = new CRacer();
        ExecutorService ser = Executors.newFixedThreadPool(2);
        Future<Integer> result1 = ser.submit(rac);
        Future<Integer> result2 = ser.submit(rac);
        Integer r1 = result1.get();
        Integer r2 = result2.get();
        System.out.println(r1 + "---->" + r2);
        ser.shutdown();
    }
}
